#!/bin/bash -e

JAR=bacnet4j/bacnet4j-1.0-SNAPSHOT-all.jar
CLASS=com.serotonin.bacnet4j.test.DiscoveryTest
TARGET="Object name = BACnet device"
TMPOUT=`tempfile`
BACNET_EXPECTED=

if [ "$1" == "loop" ]; then
    shift
    subcmd=loop
else
    subcmd=noloop
fi

# Pick the one not-lo inet v4 address.
line=$(ip addr show | fgrep "inet " | fgrep -v 127.0.0.1)

read -r -a parts <<< "$line"

local_ip=${parts[1]%/*}
broadcast_ip=${parts[3]}

echo Scanning bacnet $broadcast_ip from $local_ip

java -cp $JAR $CLASS $local_ip $broadcast_ip $subcmd | tee $TMPOUT

bacnet_runtime=/config/port/bacnet_runtime.sh
if [ -f $bacnet_runtime ]; then
    echo Processing $bacnet_runtime
    source $bacnet_runtime
fi

if [ -z "$BACNET_EXPECTED" ]; then
    # For testing, consider the presense of bacnet a failure.
    ! fgrep "$TARGET" $TMPOUT
else
    echo Bacnet expected!
    fgrep "$TARGET" $TMPOUT
fi
